"""
# prerequisite:
based on Python 3.7.x
need Python scipy & numpy module

# usage:
    1) set the variables:arr, alpha
    2) dependency_table_chi_test(arr=arr, alpha=alpha)

# process:
    1) step1: python chp3.py

# know issues:
    1) issue1

# Other
    Any issues or improvements please contact
"""
import numpy as np
from scipy.stats import chi2


def dependency_table_chi_test(arr, alpha=0.001):
    """
    标称数据的卡方检验
    :param arr:
    :param alpha: 置信水平
    :return:
    """
    def get_chi_value(observe_freqs, expect_freqs):
        """
        卡方值
        :param observe_freqs:观测频率
        :param expect_freqs:期望频率
        :return:
        """
        return np.power(observe_freqs - expect_freqs, 2) / expect_freqs

    if len(arr) == 0:
        arr = [[250, 200], [50, 1000]]

    col_df = len(arr)
    line_df = len(arr[0])

    column_sum = np.array(arr).sum(axis=0)
    line_sum = np.array(arr).sum(axis=1)
    total = np.array(arr).sum()

    chi_test_value = 0
    chi_test_value += get_chi_value(observe_freqs=arr[0][0], expect_freqs=column_sum[0] * line_sum[0] / total)
    chi_test_value += get_chi_value(observe_freqs=arr[1][0], expect_freqs=column_sum[0] * line_sum[1] / total)
    chi_test_value += get_chi_value(observe_freqs=arr[0][1], expect_freqs=column_sum[1] * line_sum[0] / total)
    chi_test_value += get_chi_value(observe_freqs=arr[1][1], expect_freqs=column_sum[1] * line_sum[1] / total)

    chi_test = chi2.isf(q=alpha, df=(col_df - 1) * (line_df - 1))

    if chi_test_value > chi_test:
        print('给定列/行属性的情况下，行/列属性相关')
    else:
        print('给定列/行属性的情况下，行/列属性无关')


if __name__ == '__main__':
    # 相依表标称数据的卡方相关性检验
    dependency_table_chi_test(arr=[])
